#include "mem_functions_folding.h"
#include "mem_functions.h"
#include "mem_structures.h"
#include "mem_macros.h"

/*
 * Create a fold around this line 
 */
void createFold(buffer_t* buffer, POSITION p)
{
    chunk_t* chunk_start = NULL;
    chunk_t* chunk_end = NULL;
    chunk_t* chunk_tmp;
    chunk_t* chunk_ptr;
    int offset=0;
    int space;
    int i=0;

    assert(buffer!=NULL);

    if(p<CHUNK_SIZE)
        DEBUG_WARN("Cant fold a single line. dummy");

    chunk_ptr = priv_get_chunk_by_position(buffer,p);
    chunk_tmp = chunk_ptr;

    /* Find the top of the code block */
    while(chunk_start==NULL&&chunk_tmp!=NULL)
    {
        for(i=chunk_tmp->length;i>=0;i--)
        {
            if(chunk_tmp->mem[i]=='{')
            {
                chunk_start=chunk_tmp;
                chunk_start->local_pos=i;   //+1?
                break;
            }
            chunk_tmp=chunk_tmp->prev;
        }
    }

    /* Find the bottom of the code block */
    chunk_tmp = chunk_ptr;
    while(chunk_end==NULL&&chunk_tmp!=NULL)
    {
        for(i=0;i<chunk_tmp->length;i++)
        {
            /* Found an embedded code block */
            if(chunk_tmp->mem[i]=='{')
            {
                offset++;
                continue;
            }
            if(chunk_tmp->mem[i]=='}')
            {
                if(offset>0)
                {
                    offset--;
                    continue;
                }
                else
                {
                    chunk_end=chunk_tmp;
                    chunk_end->local_pos = i;
                    break;
                }
            }
        }
        chunk_tmp=chunk_tmp->next;
    }

    assert(chunk_start!=NULL);
    assert(chunk_end!=NULL);

    chunk_start->type = FOLD_START;
    chunk_end->type = FOLD_END;

    /* We need to shift the data around so that the line that starts
     * the fold and the line that ends the fold are in unique chunks.
     */

    /* Find the newline character after the '{' */
    offset = chunk_start->length - chunk_start->local_pos; // chars left after '{'
    /* Check for space in the next chunk */
    space = chunk_start->next->length + offset;
    if(space < CHUNK_SIZE)
    {
        for(i=0;i<space;i++)
        {
            priv_shift_chunk_right(chunk_start->next);
        }

        memcpy(chunk_start->next->mem,&chunk_start->mem[chunk_start->local_pos],
               space * sizeof(CHARACTER));
    }
    else
    {
        priv_insert_chunk_after(chunk_start, buffer);
        memcpy(chunk_start->next->mem,&chunk_start->mem[chunk_start->local_pos],
               space * sizeof(CHARACTER));
        chunk_start->next->length=space;
    }

    for(i=CHUNK_SIZE-1;i>space;i--)
    {
        chunk_start->mem[i]='\0';
        chunk_start->length--;
    }

    /*
     * Sublist out the folded chunks
     */

    /* Erm... done */

}

void unfold(buffer_t* buffer, POSITION p)
{}
